package com.message;

import com.util.LogUtil;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * Created by Mars on 2017/9/21.
 */

public class UserMessageDecoder extends CumulativeProtocolDecoder {

    public UserMessageDecoder() {
    }

    @Override
    protected boolean doDecode(IoSession session, IoBuffer in,
                               ProtocolDecoderOutput out) throws Exception {
        if (in.remaining() >= MsgHead.HEAD_SIZE) {
            in.mark();
            //获取数据包长度
            short packageLen = in.getShort();
            short packageInstruction = in.getShort();
            short usMsgType = in.getShort();
            short packageOrderNum = in.getShort();
            LogUtil.e("packageLen = " + packageLen);

            int usBodyLen = packageLen - 8;
            int i = usBodyLen;

            if (i < 0) {
                i = (i & Short.MAX_VALUE) + Short.MAX_VALUE + 1;
            }

            if (i > in.remaining()) {
                if (!in.isAutoExpand()) {
                    in.setAutoExpand(true);
                }
                in.reset();
                return false;
            } else {
                MsgPacket packet = new MsgPacket(usMsgType);

                if (i > 0) {
                    byte[] bodyBytes = new byte[i];
                    in.get(bodyBytes, 0, i);
                    packet.setBody(new String(bodyBytes));
                }

                out.write(packet);
                LogUtil.e("doDecode-" + packet);

                if (in.remaining() > 0) {
                    return true;
                }
            }

//            if (in.remaining() < packageLen - MsgHead.HEAD_SIZE) {
//                //内容不够， 重置position到操作前，进行下一轮接受新数据
//                in.reset();
//                return false;
//            } else {
//                //内容足够
//                in.reset(); //重置回复position位置到操作前
//                byte[] packArray = new byte[packageLen];
//                in.get(packArray, 0, packageLen); //获取整条报文
//
//                //根据自己需要解析接收到的东西
//                String str = new String(packArray);
//                out.write(str); //发送出去 就算完成了
//
//                if (in.remaining() > 0) {//如果读取一个完整包内容后还粘了包，就让父类再调用一次，进行下一次解析
//                    return true;
//                }
//
//            }
        }
        return false;
    }
}